package com.youku.expression.environment;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class BaseEnvironment implements Environment {
	
	private static final Logger logger=LoggerFactory.getLogger(BaseEnvironment.class);

	protected Map<String, Object> var;

	protected Environment outer;

	public BaseEnvironment(Environment outer) {
		this();
		this.outer = outer;
	}

	public BaseEnvironment() {
		var = new HashMap<>();
	}

	@Override
	public void put(String key, Object value) {
		logger.info("给key:{}设置value:{}",key,value==null?"null":value.toString());
		var.put(key, value);
	}

	@Override
	public Object get(String key) {
		return var.get(key);
	}

	@Override
	public void setOuter(Environment outer) {
		this.outer = outer;
	}

	@Override
	public Environment getOuter() {
		return outer;
	}

	@Override
	public Map<String, Object> iterator() {
		return var;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();

		if (var == null)
			return builder.toString();

		for (Entry<String, Object> entry : iterator().entrySet()) {
			builder.append('\n').append(entry.getKey() + ":" + entry.getValue());
		}

		return builder.toString();
	}

}
